package com.ants.project.core.spider.samples;

import com.alibaba.fastjson.JSON;
import com.ants.project.core.utils.FileUtil;
import com.ants.project.core.utils.MyDBUtil;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.*;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.processor.PageProcessor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 抓取http://www.phpxs.com/
 * Created by zhituliu on 2016/4/7.
 */
public class PhpxsProcesser implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(100).setTimeOut(3000).setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0");

    private static MyDBUtil dbUtils = new MyDBUtil();

    //回调储存到数据库
    public static class DataFilePipeline implements Pipeline {

        @Override
        public void process(ResultItems resultItems, Task task) {
            Map map = resultItems.getAll();
            if(map.size()!=0) {
                Object imgs = map.get("imgs");
                if(imgs!=null){
                    List<String> list = (List)imgs;
                    for(String img:list) {
                        if(img.indexOf("http://")!=-1){
                            System.out.println("## 外连接无法下载 ~~");
                        }else {
                            FileUtil.download("http://www.phpxs.com" + img, "d:" + img.replaceAll("uploads", "zb_users/upload"));
                            System.out.println(img+" 下载完成 success!");
                        }
                    }
                }
                try {
                    dbUtils.insert("insert into ls_post(log_CateID,log_AuthorId,log_Title,log_Intro,log_Content,log_PostTime,log_ViewNums,log_Meta) values(?,?,?,?,?,?,?,?)"
                        ,new ScalarHandler(),24,1,map.get("title").toString(),map.get("intro").toString(),map.get("content").toString(),Integer.parseInt(map.get("time").toString()),Integer.parseInt(map.get("number").toString()),"");
                    System.out.println(count + map.get("title").toString()+" 数据插入完成!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
    // 去标签方法
    public String deleteTag(String content) {
        StringBuffer sb = new StringBuffer(content);
        if(StringUtils.isEmpty(content))
            return "";
        else{
            while (sb.indexOf("<") != -1) {
                int start = sb.indexOf("<");
                int end = sb.indexOf(">", start  + 1);
                String a = sb.substring(start, end + 1);
                sb.delete(start, end+1);
                if(sb.indexOf("<") == -1)
                    break;
            }
            return sb.toString().replaceAll("\n", "").replaceAll("\r","").replaceAll(" ","").trim();
        }

    }
    static int count = 0;
    @Override
    public void process(Page page) {
        List links = page.getHtml().xpath("div[@id=\"content\"]").links().regex("(http://www\\.phpxs\\.com/post/\\w+)").all();
        page.addTargetRequests(links);
        if(count>0) {
            page.putField("title", page.getHtml().xpath("//h1[@class=\"entry-title\"]//text()"));
            page.putField("number", page.getHtml().xpath("//i[@id=\"number\"]//text()"));
            String time = page.getHtml().xpath("//time[@class=\"date updated\"]/text()").toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                page.putField("time", String.valueOf(sdf.parse(time).getTime()).substring(0,10));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String content = page.getHtml().xpath("//div[@class=\"article-entry phpxs_content 20160112\"]").toString();
            page.putField("url", page.getUrl().toString());
            String intro = deleteTag(content.trim()).substring(0,230);
            page.putField("intro", intro.replaceAll("\n","").replaceAll("\t","").replaceAll("\\s","").replaceAll("\r","").trim());
            page.putField("content", content.replaceAll("uploads","zb_users/upload"));
            List<String> listProcess = page.getHtml().xpath("//div[@class=\"article-entry phpxs_content 20160112\"]//img/@src").all();
            page.putField("imgs", listProcess);
            System.out.println(page.getUrl().toString());
            System.out.println(JSON.toJSON(listProcess));
        }
        count++;
        System.out.println(count);


    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] ags) throws ParseException {
      //  for(int i=1;i<=2;i++) {
            Spider.create(new PhpxsProcesser()).addUrl("http://www.phpxs.com/post/programmer/1").addPipeline(new DataFilePipeline()).thread(5).run();
        //    System.out.println("############################### 第 "+i+" 页");
      //  }
    }
}

